﻿using AgileConfig.Client.RegisterCenter;
using Ocelot.Configuration;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using System;

namespace Service.Gateway.Core.AgileConfigServiceDiscovery
{
    /// <summary>
    /// 自定义AgileConfig服务发现
    /// </summary>
    public class AgileConfigServiceDiscoveryProvider : IServiceDiscoveryProvider
    {
        private readonly IDiscoveryService _discoveryService;
        private readonly DownstreamRoute _downstreamRoute;
        public async Task<List<Ocelot.Values.Service>> GetAsync()
        {
            var discoveryServiceServices = _discoveryService.Services.Where(s => s.ServiceName.Equals(_downstreamRoute.ServiceName));
            return await Task.FromResult(discoveryServiceServices.Select(s => new Ocelot.Values.Service(s.ServiceName, new ServiceHostAndPort(s.Ip, s.Port.HasValue ? s.Port.Value : 80), s.ServiceId, "1.0.0.0", null)).ToList());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="discoveryService"></param>
        /// <param name="config"></param>
        /// <param name="downstreamRoute"></param>
        public AgileConfigServiceDiscoveryProvider(IDiscoveryService discoveryService, DownstreamRoute downstreamRoute)
        {
            _discoveryService = discoveryService;
            _downstreamRoute = downstreamRoute;
        }
    }
}
